from grid_env_ideal_obs_repeat_task import *
from grid_agent import *
from checkpoint_utils import *
from maze_factory import *
from replay_config import *
import argparse
import json
import sys
import matplotlib.pyplot as plt
from sklearn.manifold import TSNE
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.patches import Circle
from matplotlib.lines import Line2D
from sklearn.manifold import TSNE
import random
from sklearn.decomposition import PCA
from matplotlib.animation import FuncAnimation
from sklearn.cluster import KMeans
import threading
import mplcursors
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
from scipy.spatial import KDTree
from sklearn.linear_model import LinearRegression
import umap
from ripser import ripser
from persim import plot_diagrams
from scipy.spatial.distance import pdist, squareform


def progress_bar(current, total, barLength = 100):
    percent = float(current) * 100 / total
    arrow = '-' * int(percent/100 * barLength - 1) + '>'
    spaces = ' ' * (barLength - len(arrow))

    print('Progress: [%s%s] %d %%' % (arrow, spaces, percent), end='\r')
    sys.stdout.flush()

@partial(jax.jit, static_argnums=(3,))
def model_forward(variables, state, x, model):
    """ forward pass of the model
    """
    return model.apply(variables, state, x)

@jit
def get_action(y):
    return jnp.argmax(y)
get_action_vmap = jax.vmap(get_action)

# load landscape and states from file
def load_task(pth = "./logs/task.json", display = True):
    # open json file
    with open(pth, "r") as f:
        data = json.load(f)
        landscape = data["data"]
        state = data["state"]
        goal = data["goal"]
        if display:
            print("state: ", state)
            print("goal: ", goal)
            print("landscape: ", landscape)
    return landscape, state, goal

def main():

    """ parse arguments
    """
    rpl_config = ReplayConfig()

    parser = argparse.ArgumentParser()
    parser.add_argument("--model_pth", type=str, default=rpl_config.model_pth)
    parser.add_argument("--map_size", type=int, default=rpl_config.map_size)
    parser.add_argument("--task_pth", type=str, default=rpl_config.task_pth)
    parser.add_argument("--log_pth", type=str, default=rpl_config.log_pth)
    parser.add_argument("--nn_size", type=int, default=rpl_config.nn_size)
    parser.add_argument("--nn_type", type=str, default=rpl_config.nn_type)
    parser.add_argument("--show_kf", type=str, default=rpl_config.show_kf)
    parser.add_argument("--visualization", type=str, default=rpl_config.visualization)
    parser.add_argument("--video_output", type=str, default=rpl_config.video_output)
    parser.add_argument("--life_duration", type=int, default=rpl_config.life_duration)

    args = parser.parse_args()

    rpl_config.model_pth = args.model_pth
    rpl_config.map_size = args.map_size
    rpl_config.task_pth = args.task_pth
    rpl_config.log_pth = args.log_pth
    rpl_config.nn_size = args.nn_size
    rpl_config.nn_type = args.nn_type
    rpl_config.show_kf = args.show_kf
    rpl_config.visualization = args.visualization
    rpl_config.video_output = args.video_output
    rpl_config.life_duration = args.life_duration

    nn_type = ''
    if rpl_config.nn_type == "vanilla":
        nn_type = "vanilla"
    elif rpl_config.nn_type == "gru":
        nn_type = "gru"

    def load_data(nn_type, seq_len, redundancy, diverse_set_capacity):

        rnn_limit_rings_file_name = "./logs/rnn_limit_ring_collection_" + nn_type + "_" + str(seq_len) + "_" + str(redundancy) + "_" + str(diverse_set_capacity) + ".npz"

        # 载入 npz 文件
        rnn_limit_rings_file = np.load(rnn_limit_rings_file_name)

        # 获取 npz 文件中的所有对象名称
        matrix_names = rnn_limit_rings_file.files

        rnn_limit_rings = []

        # 遍历对象名称，访问和操作每个矩阵对象
        for name in matrix_names:
            matrix = rnn_limit_rings_file[name]
            rnn_limit_rings.append(matrix)
            # print("shape of matrix: ", np.shape(matrix))

        rnn_limit_rings = np.array(rnn_limit_rings)
        return rnn_limit_rings
    
    configs = [

        [nn_type, 6, 1, 100],
        [nn_type, 7, 1, 100],
        # [nn_type, 8, 1, 100],
        # [nn_type, 9, 1, 100],
        # [nn_type, 10, 1, 100],
        # [nn_type, 11, 1, 100],
        # [nn_type, 12, 1, 100],
        # [nn_type, 13, 1, 100],
        # [nn_type, 14, 1, 100],
        # [nn_type, 15, 1, 100],
        
        ]
    
    rnn_limit_rings_collection = []
    for i in range(len(configs)):
        raw_data_matrix = load_data(configs[i][0], configs[i][1], configs[i][2], configs[i][3])
        raw_data_linear = raw_data_matrix.reshape(raw_data_matrix.shape[0]*raw_data_matrix.shape[1]*raw_data_matrix.shape[2]*raw_data_matrix.shape[3],raw_data_matrix.shape[4])
        rnn_limit_rings_collection.append(raw_data_linear)

    # 将 rnn_limit_rings_collection 的所有元素拼接起来
    rnn_limit_rings_collection_all = np.concatenate(rnn_limit_rings_collection, axis=0)
    rnn_limit_rings_collection_0 = rnn_limit_rings_collection[0]
    rnn_limit_rings_collection_1 = rnn_limit_rings_collection[1]
    print("shape of rnn_limit_rings_collection_all: ", rnn_limit_rings_collection_all.shape)

    # 对 rnn_limit_rings_collection 进行PCA
    pca = PCA()
    pca.fit(rnn_limit_rings_collection_all)
    rnn_limit_rings_collection_pca = pca.transform(rnn_limit_rings_collection_all)
    rnn_limit_rings_collection_0_pca = pca.transform(rnn_limit_rings_collection_0)
    rnn_limit_rings_collection_1_pca = pca.transform(rnn_limit_rings_collection_1)

    # 获取 pca 的 explained_variance_ratio_
    explained_variance_ratio_ = pca.explained_variance_ratio_
    # 将 explained_variance_ratio_ 绘制成 bar chart
    plt.figure(figsize=(10, 10))
    plt.bar(range(len(explained_variance_ratio_)), explained_variance_ratio_)
    plt.show()

    # 随机选取 10000 个点，并进行可视化
    n_samples = 10000
    rnd_idx_all = np.random.choice(rnn_limit_rings_collection_pca.shape[0], n_samples, replace=False)
    rnd_idx_0 = np.random.choice(rnn_limit_rings_collection_0_pca.shape[0], n_samples, replace=False)
    rnd_idx_1 = np.random.choice(rnn_limit_rings_collection_1_pca.shape[0], n_samples, replace=False)
    rnn_limit_rings_collection_pca = rnn_limit_rings_collection_pca[rnd_idx_all]
    rnn_limit_rings_collection = rnn_limit_rings_collection_all[rnd_idx_all]
    rnn_limit_rings_collection_0_pca = rnn_limit_rings_collection_0_pca[rnd_idx_0]
    rnn_limit_rings_collection_1_pca = rnn_limit_rings_collection_1_pca[rnd_idx_1]

    fig = plt.figure(figsize=(10, 10))
    ax = fig.add_subplot(111, projection='3d')
    # ax.scatter(rnn_limit_rings_collection_pca[:, 0], rnn_limit_rings_collection_pca[:, 1], rnn_limit_rings_collection_pca[:, 2], s=1)
    ax.scatter(rnn_limit_rings_collection_0_pca[:, 0], rnn_limit_rings_collection_0_pca[:, 1], rnn_limit_rings_collection_0_pca[:, 2], s=1, c='r')
    ax.scatter(rnn_limit_rings_collection_1_pca[:, 0], rnn_limit_rings_collection_1_pca[:, 1], rnn_limit_rings_collection_1_pca[:, 2], s=1, c='b')
    plt.show()

    return

    fig = plt.figure(figsize=(10, 10))
    ax = fig.add_subplot(111, projection='3d')
    ax.scatter(rnn_limit_rings_collection_pca[:, 3], rnn_limit_rings_collection_pca[:, 4], rnn_limit_rings_collection_pca[:, 5], s=1)
    plt.show()

    # # 对 rnn_limit_rings_collection_pca 保留前 6 个主成分，然后 inverse_transform
    # rnn_limit_rings_collection_pca[:, 6:] = 0
    # rnn_limit_rings_collection = pca.inverse_transform(rnn_limit_rings_collection_pca)

    # 对 rnn_limit_rings_collection 进行 UMAP
    reducer = umap.UMAP(n_components=3, n_neighbors=20, min_dist=0.1, init='spectral')
    rnn_limit_rings_collection_umap = reducer.fit_transform(rnn_limit_rings_collection)

    fig = plt.figure(figsize=(10, 10))
    ax = fig.add_subplot(111, projection='3d')
    ax.scatter(rnn_limit_rings_collection_umap[:, 0], rnn_limit_rings_collection_umap[:, 1], rnn_limit_rings_collection_umap[:, 2], s=1)
    plt.show()

    # fig = plt.figure(figsize=(10, 10))
    # ax = fig.add_subplot(111, projection='3d')
    # ax.scatter(rnn_limit_rings_collection_umap[:, 3], rnn_limit_rings_collection_umap[:, 4], rnn_limit_rings_collection_umap[:, 5], s=1)
    # plt.show()

    # dist_matrix = squareform(pdist(rnn_limit_rings_collection, 'euclidean'))
    # dgms = ripser(dist_matrix, maxdim=1, coeff=47,do_cocycles= True, distance_matrix=True)['dgms']
    # plot_diagrams(dgms, show=True, lifetime=True)
    
if __name__ == "__main__":
    main()
